﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 中文转Unicode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string str = textBox1.Text;

            string ucode = String2Unicode(str);

            textBox2.Text = ucode;
        }

        public string String2Unicode(string source)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(source);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i += 2)
            {
                stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
            }
            return stringBuilder.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string str = textBox2.Text;
            if(str != null && str.Length>0)
            {
                textBox2.Copy();
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            string str = uiTextBox1.Text;
            string ucode = StringUtil.String2Unicode(str);
            uiTextBox2.Text = ucode;
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            string str = uiTextBox2.Text;
            if(str != null && str.Length>0)
            {
                uiTextBox2.Copy();
            }
        }
    }

    public class StringUtil
    {
        public static string String2Unicode(string source)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(source);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i += 2)
            {
                stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
            }
            return stringBuilder.ToString();
        }
    }
}
